package com.demo.common.core.response;
import cn.hutool.core.util.StrUtil;
import com.demo.common.core.exception.ResponseCode;
import com.demo.common.core.exception.ResponseErrorCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import java.util.Objects;

@NoArgsConstructor
@AllArgsConstructor
@Getter
public class Response<T>{

    private int code;

    private int errorCode;

    private String msg;

    private T data;


    private static <T> Response<T> result(@NonNull ResponseCode code, @Nullable ResponseErrorCode errorCode, @Nullable String msg, @Nullable T data){
        if(Objects.isNull(errorCode)){
            return new Response<T>(code.getCode(), code.getCode(), StrUtil.isNotBlank(msg)?msg:code.getMsg(), data);
        }
        return new Response<T>(code.getCode(), errorCode.getErrorCode(), StrUtil.isNotBlank(msg)?msg:errorCode.getMsg(), data);
    }


    public static <T> Response<T> ok(T data){return result(ResponseCode.SUCCESS, ResponseErrorCode.SUCCESS, null, data);}
    public static <T> Response<T> ok(){return ok(null);}

    public static <T> Response<T> fail(ResponseErrorCode errorCode, String msg, T data){return result(ResponseCode.FAIL, errorCode, msg, data);}
    public static <T> Response<T> fail(ResponseErrorCode errorCode, String msg){return fail(errorCode, msg, null);}
    public static <T> Response<T> fail(ResponseErrorCode errorCode){return fail(errorCode, null);}
    public static <T> Response<T> failWithData(ResponseErrorCode errorCode, T data){return fail(errorCode, null, data);}
}
